//
//  KLSGPlayRadioViewController.m
//  KaoLaShiGuangFM
//
//  Created by lanou3g on 15/10/31.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "KLSGPlayRadioViewController.h"
#import "KLSGPlayModel.h"
#import "KLSGRadioPlayManager.h"
#import "KLSGPlayerView.h"
#import "KLSGDataFail.h"
#import "AppDelegate.h"
#import "UIButton+WebCache.h"
#import "DDIndicator.h"
#import "Reachability.h"

#define kImageX 90

@interface KLSGPlayRadioViewController ()<KLSGRadioPlayManagerDelegate>
{
    // 设置接收传进来的index 取出对应model
    NSNumber *currentId;
    // 播放状态切换标记
    BOOL isPlaying;
}

// 声明数组属性,存放model
@property (nonatomic, strong) NSMutableArray *allDataArray;
// 内容标题
@property (nonatomic, strong) UILabel *playTitle;
// 时间
@property (nonatomic, strong) UILabel *playTime;
// 进度条时间
@property (nonatomic, strong) NSString *startTime;
@property (nonatomic, strong) NSString *endTime;
// 进度条
@property (nonatomic, strong) UISlider *sliderView;
@property (nonatomic, strong) UISlider *scheduleSliderView;
// 播放暂停按钮
@property (nonatomic, strong) UIButton *playOrPauseButton;
// 图片
@property (nonatomic, strong) UIImageView *playImageView;

@property (nonatomic, strong) UIImageView *bgImageView;

// 标题
@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) KLSGDataFail *dataFailView;
// AVPlayer
@property (nonatomic, strong) KLSGRadioPlayManager *player;

@property (nonatomic, strong) KLSGMainViewController *mainVC;
// 加载指示器
@property (nonatomic, strong) DDIndicator *indicator;
// 网络连接
@property (nonatomic, strong) Reachability *conn;

@property (nonatomic, assign) BOOL isConn; // 记录网络状态

@end

@implementation KLSGPlayRadioViewController

- (void)dealloc
{
    [self.conn stopNotifier];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.tabBarController.tabBar.hidden = YES;
    if ([currentId intValue] == [_radioId intValue]) {
        return;
    } else {
        [self updataUI];
    }
}

// 刷新界面
- (void)updataUI
{
    self.playTime.text = @"";
    NSString *url;
    switch (self.type) {
        case VoiceTypeGeneral:
        {
            // 设置标题
            self.titleLabel.text = self.albumModel.albumTitle;
            KLSGListModel *model = self.radioModelArray[self.index];
            currentId = model.trackId;
            self.radioId = model.trackId;
            url = model.playPathAacv164;
            
            self.scheduleSliderView.minimumValue = 0;
            self.scheduleSliderView.maximumValue = [model.duration floatValue];
            
             [_mainVC.playBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:model.coverSmall] forState:(UIControlStateNormal) placeholderImage:[UIImage imageNamed:@"place"]];
            [_mainVC.icon sd_setImageWithURL:[NSURL URLWithString:model.coverSmall]];
            [_playImageView sd_setImageWithURL:[NSURL URLWithString:model.coverMiddle] placeholderImage:[UIImage imageNamed:@"place"]];
            
            self.playTitle.text = model.title;

        }
            break;
        case VoiceTypeHot:
        {
            self.hotModel = self.radioModelArray[self.index];
            self.titleLabel.text = self.hotModel.albumTitle;
            currentId = _hotModel.uid;
            self.radioId = _hotModel.uid;
            url = _hotModel.playPath32;
            
            self.scheduleSliderView.minimumValue = 0;
            self.scheduleSliderView.maximumValue = [_hotModel.duration floatValue];
            
             [_mainVC.playBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:self.hotModel.coverSmall] forState:(UIControlStateNormal) placeholderImage:[UIImage imageNamed:@"place"]];
            [_mainVC.icon sd_setImageWithURL:[NSURL URLWithString:self.hotModel.coverSmall]];
            [_playImageView sd_setImageWithURL:[NSURL URLWithString:_hotModel.coverSmall] placeholderImage:[UIImage imageNamed:@"place"]];
            
            self.playTitle.text = _hotModel.title;
        }
            break;
        case VoiceTypeRadio:
        {
            KLSGRadioModel *model = [self getRadioModelWithIndex:_index];
             [_mainVC.playBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:model.radioCoverLarge] forState:(UIControlStateNormal) placeholderImage:[UIImage imageNamed:@"place"]];
            [_mainVC.icon sd_setImageWithURL:[NSURL URLWithString:model.radioCoverLarge]];
            currentId = model.radioId;
            self.radioId = model.radioId;
            // 设置标题
            self.titleLabel.text = model.rname;
            // 解析数据，刷新界面
            [self setUpData];
            url = model.radioPlayUrl[@"radio_24_aac"];
        }
            break;
        case VoiceTypeVoice:
        {
            self.voiceModel = self.radioModelArray[self.index];
            self.titleLabel.text = self.voiceModel.albumTitle;
            currentId = _voiceModel.trackId;
            self.radioId = _voiceModel.trackId;
            url = _voiceModel.playUrl32;
            
            self.scheduleSliderView.minimumValue = 0;
            self.scheduleSliderView.maximumValue = [_voiceModel.duration floatValue];
            
            [_mainVC.playBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:self.voiceModel.coverSmall] forState:(UIControlStateNormal) placeholderImage:[UIImage imageNamed:@"place"]];
            [_mainVC.icon sd_setImageWithURL:[NSURL URLWithString:self.voiceModel.coverSmall]];
            [_playImageView sd_setImageWithURL:[NSURL URLWithString:_hotModel.coverSmall] placeholderImage:[UIImage imageNamed:@"place"]];
            
            self.playTitle.text = _voiceModel.title;
            
        }
            break;
            
        default:
            break;
    }

    if (url.length != 0) {
        // 初始化AVPlayer
        [self initPlayerWithUrl:url];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = [UIColor whiteColor];
    // 布局
    [self addSubViews];
    // 创建AVPlayer
    self.player = [KLSGRadioPlayManager shareManager];
    
    // 设置代理
    self.player.delegate = self;
    [self.player addObserver:self forKeyPath:@"isPlaying" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil];
    
    // 获得mainVC
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    self.mainVC = app.mainVC;
    
    // 监听网络连接
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
    self.conn = [Reachability reachabilityForInternetConnection];
    [self.conn startNotifier];
    [self networkStateChange];
}

// 检测网络连接状况
- (void)networkStateChange
{
    [self checkNetworkState];
}

- (void)checkNetworkState
{
        // 1.检测wifi状态
        Reachability *wifi = [Reachability reachabilityForLocalWiFi];

        // 2.检测手机是否能上网络(WIFI\3G\2.5G)
        Reachability *conn = [Reachability reachabilityForInternetConnection];
    
        // 3.判断网络状态
        if ([wifi currentReachabilityStatus] != NotReachable)
        { // 有wifi
            NSLog(@"有wifi");
            self.isConn = YES;
        } else if ([conn currentReachabilityStatus] != NotReachable)
            { // 没有使用wifi, 使用手机自带网络进行上网
                self.isConn = YES;
            } else
            { // 没有网络
                self.isConn = NO;
            }
}

#pragma mark - 播放器
- (void)initPlayerWithUrl:(NSString *)url
{
    if (self.isConn) {
        [self.player.playerItem removeObserver:self forKeyPath:@"playbackBufferEmpty"];
        [self.player.playerItem removeObserver:self forKeyPath:@"playbackLikelyToKeepUp"];
        
        [self.indicator startAnimating];
        // 设置播放器
        [self.player playingWithUrl:url];
        [self.player.playerItem addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil];
        [self.player.playerItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew  context:nil];
    } else
    {
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"" message:@"请链接网络..." preferredStyle:(UIAlertControllerStyleAlert)];
        [self presentViewController:alertView animated:YES completion:nil];
        [self performSelector:@selector(dismissAlert:) withObject:alertView afterDelay:2];
    }
    
}

#pragma mark - 解析数据
- (void)setUpData
{
    // 1.创建session对象  NSURLSession
    NSURLSession *session = [NSURLSession sharedSession];
    // 2.创建网址对象
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://live.ximalaya.com/live-web/v1/getProgramDetail?device=iPhone&programScheduleId=5221&radioId=%@", [self getRadioModelWithIndex:self.index].radioId]];
    // 3.根据URL创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 4.建立会话 NSURLSessionDataTask
    // block中要使用self 需要用__block修饰一下
    __block KLSGPlayRadioViewController *mySelf = self;
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        // 5.解析
        if (data != nil) {
            NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            // 取出需要的数据
            NSDictionary *resultDic = dic[@"result"];
            
            // 回到主线程赋值
            dispatch_async(dispatch_get_main_queue(), ^{
                
                // 赋值
                if (resultDic[@"programName"] == nil) {
                    mySelf.playTitle.text = @"正在直播: 暂无节目单";
                    mySelf.playTime.text = @"00:00~24:00";
                    mySelf.startTime = @"00:00";
                    mySelf.endTime = @"24:00";
                } else {
                    mySelf.playTitle.text = [NSString stringWithFormat:@"正在直播: %@", resultDic[@"programName"]];
                    mySelf.playTime.text = [NSString stringWithFormat:@"%@~%@", resultDic[@"startTime"], resultDic[@"endTime"]];
                    mySelf.startTime = resultDic[@"startTime"];
                    mySelf.endTime = resultDic[@"endTime"];
                    // 设置进程条的范围
                    float min = 0, max = 0;
                    NSArray *minArray = [mySelf.startTime componentsSeparatedByString:@":"];
                    min = [minArray[0] floatValue] * 60 * 60 + [minArray[1] floatValue] * 60;
                    NSArray *maxArray = [mySelf.endTime componentsSeparatedByString:@":"];
                    max = [maxArray[0] floatValue] * 3600 + [maxArray[1] floatValue] * 60;
                    mySelf.scheduleSliderView.minimumValue = 0;
                    mySelf.scheduleSliderView.maximumValue = max - min;
                }
                
                _playImageView.backgroundColor = [UIColor lightGrayColor];
                [_playImageView sd_setImageWithURL:[NSURL URLWithString:[self getRadioModelWithIndex:_index].radioCoverLarge] placeholderImage:[UIImage imageNamed:@"place"]];
                
            });
            
        } else {
            [mySelf performSelectorOnMainThread:@selector(failAction) withObject:nil waitUntilDone:YES];
        }
        
    }];
    
    // 6.启动解析
    [task resume];
}

#pragma mark - 重新加载数据
- (void)failAction
{
    self.dataFailView = [[KLSGDataFail alloc] initWithFrame:CGRectMake(0, 200, kScreenWidth, 300)];
    [self.view addSubview:_dataFailView];
    [self.dataFailView netRequestFailWithBlock:^{
        [self setUpData];
        [_dataFailView hidden];
    }];
}

#pragma mark - 创建布局
- (void)addSubViews
{
    self.view.backgroundColor = [UIColor colorWithRed:247 / 256.0 green:242 / 256.0 blue:236 / 256.0 alpha:1];
    // 1.背景图片
    UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight/2 - 20)];
    // 打开交互
    bgImageView.userInteractionEnabled = YES;
    bgImageView.image = [UIImage imageNamed:@"background"];
    [self.view addSubview:bgImageView];
    self.bgImageView = bgImageView;
    
    // 2.图片
    self.playImageView = [[UIImageView alloc] initWithFrame:CGRectMake(kImageX, (bgImageView.frame.size.height-(kScreenWidth - kImageX * 2))/2, kScreenWidth - kImageX * 2, kScreenWidth - kImageX * 2)];
    // 设置圆角
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:_playImageView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(20, 0)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = _playImageView.bounds;
    maskLayer.path = maskPath.CGPath;
    _playImageView.layer.mask = maskLayer;
    _playImageView.alpha = 0.6;
    [bgImageView addSubview:_playImageView];
    
    // 3.内容标题
    self.playTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, bgImageView.frame.origin.y + bgImageView.frame.size.height + 20, kScreenWidth - 20, 30)];
    _playTitle.textColor = [UIColor colorWithRed:234 / 256.0 green:79 / 256.0 blue:56 / 256.0 alpha:1];
    _playTime.font = [UIFont systemFontOfSize:30.0];
    _playTitle.textAlignment = YES;
    [self.view addSubview:_playTitle];
    
    // 4.时间
    self.playTime = [[UILabel alloc] initWithFrame:CGRectMake(bgImageView.frame.origin.x + (bgImageView.frame.size.width - 200)/2, bgImageView.frame.origin.y + bgImageView.frame.size.height + 60, 200, 30)];
    _playTime.textColor = [UIColor colorWithRed:234 / 256.0 green:79 / 256.0 blue:56 / 256.0 alpha:1];
    _playTime.textAlignment = YES;
    [self.view addSubview:_playTime];
    
    // 5.进度条调节音量
    self.sliderView = [[UISlider alloc] initWithFrame:CGRectMake(40, (kScreenHeight/4)*3 + 10, kScreenWidth-80, 30)];
    _sliderView.minimumTrackTintColor = [UIColor colorWithRed:234 / 256.0 green:79 / 256.0 blue:56 / 256.0 alpha:1];
    [_sliderView addTarget:self action:@selector(actionVolume:) forControlEvents:(UIControlEventValueChanged)];
    _sliderView.maximumValue = 10;
    _sliderView.value = 1.0;
    [self.view addSubview:_sliderView];
    
    // 6.进度条
    self.scheduleSliderView = [[UISlider alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(bgImageView.frame) - 15, kScreenWidth, 30)];
    _scheduleSliderView.minimumTrackTintColor = [UIColor colorWithRed:234 / 256.0 green:79 / 256.0 blue:56 / 256.0 alpha:1];
    [_scheduleSliderView addTarget:self action:@selector(schedule:) forControlEvents:(UIControlEventValueChanged)];
    [self.view addSubview:_scheduleSliderView];
    
    // 7.音量imageView
    UIImageView *volumeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, (kScreenHeight/4)*3+8, 30, 30)];
    volumeImageView.image = [UIImage imageNamed:@"yinliang0"];
    [self.view addSubview:volumeImageView];
    
    // 8.button
    // 上一首
    UIButton *prevButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    prevButton.frame = CGRectMake((kScreenWidth - 200)/2, (kScreenHeight/4)*3+50, 40, 40);
    [prevButton setImage:[UIImage imageNamed:@"shang1"] forState:(UIControlStateNormal)];
    [prevButton addTarget:self action:@selector(actionPreviousButton) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:prevButton];
    // 下一首
    UIButton *nextButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    nextButton.frame = CGRectMake(kScreenWidth/2 + 100 - 40, (kScreenHeight/4)*3+50, 40, 40);
    [nextButton setImage:[UIImage imageNamed:@"xia1"] forState:(UIControlStateNormal)];
    [nextButton addTarget:self action:@selector(actionNextButton) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:nextButton];
    // 播放暂停
    self.playOrPauseButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _playOrPauseButton.frame = CGRectMake(kScreenWidth/2 - 25, (kScreenHeight/4)*3+50, 50, 50);
    [_playOrPauseButton setImage:[UIImage imageNamed:@"bofang"] forState:(UIControlStateNormal)];
    [_playOrPauseButton addTarget:self action:@selector(actionPlayOrPause:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_playOrPauseButton];
    
    // 添加加载指示器
    self.indicator = [[DDIndicator alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    self.indicator.center = CGPointMake(CGRectGetWidth(self.playOrPauseButton.frame) / 2, CGRectGetHeight(self.playOrPauseButton.frame) / 2);
    self.indicator.userInteractionEnabled = NO;
    [self.playOrPauseButton addSubview:self.indicator];
    
    // 设置返回按钮
    UIButton *backBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    backBtn.frame = CGRectMake(10, 20, 50, 40);
    [backBtn setImage:[UIImage imageNamed:@"play_dismiss"] forState:(UIControlStateNormal)];
    [backBtn addTarget:self action:@selector(back:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:backBtn];
    
    // 标题
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 20, kScreenWidth - 140, 40)];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.titleLabel];
}

- (void)back:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 控件点击方法实现
#pragma mark - 播放暂停
- (void)actionPlayOrPause:(UIButton *)button
{
    BOOL isplay = [[KLSGRadioPlayManager shareManager] musicPlayOrPause];
    if (isplay) {
        [_playOrPauseButton setImage:[UIImage imageNamed:@"zanting"] forState:(UIControlStateNormal)];
    } else {
        [_playOrPauseButton setImage:[UIImage imageNamed:@"bofang"] forState:(UIControlStateNormal)];
    }
}

#pragma mark -播放状态改变

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if (object == self.player && self.player.isPlaying) {
        _mainVC.picture.image = [UIImage imageNamed:@"play_bg_new"];
        [_playOrPauseButton setImage:[UIImage imageNamed:@"zanting"] forState:(UIControlStateNormal)];
        _mainVC.icon.hidden = NO;
    } else if (object == self.player && !self.player.isPlaying){
        _mainVC.picture.image = [UIImage imageNamed:@"play_icon_new"];
        [_playOrPauseButton setImage:[UIImage imageNamed:@"bofang"] forState:(UIControlStateNormal)];
        _mainVC.icon.hidden = YES;
    }
    
    if (object == self.player.playerItem && [keyPath isEqualToString:@"playbackBufferEmpty"])
    {
        if (self.player.playerItem.playbackBufferEmpty) {
            //Your code here
            [self.indicator startAnimating];
            [self.player musicPause];
        }
    }
    
    else if (object == self.player.playerItem && [keyPath isEqualToString:@"playbackLikelyToKeepUp"])
    {
        if (self.player.playerItem.playbackLikelyToKeepUp)
        {
            //Your code here
            [self.indicator stopAnimating];
            [self.player musicPlay];
        }
    }
}

#pragma mark - 上一曲
- (void)actionPreviousButton
{
        self.index--;
        if (self.index < 0) {
            self.index = self.radioModelArray.count - 1;
        }
        [self updataUI];
}

- (void)dismissAlert:(UIAlertController *)alert
{
    [alert dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 下一曲
- (void)actionNextButton
{
        self.index++;
        if (self.index >= self.radioModelArray.count) {
            self.index = 0;
        }
        [self updataUI];
}

#pragma mark - 调节音量
- (void)actionVolume:(UISlider *)slider
{
    [KLSGRadioPlayManager shareManager].player.volume = slider.value;
}

#pragma mark -调节进度
- (void)schedule:(UISlider *)slider
{
    [self.player musicSeekToTime:slider.value];
}

#pragma mark - 获取当前radioModel
- (KLSGRadioModel *)getRadioModelWithIndex:(NSInteger)index
{
    KLSGRadioModel *radioModel = self.radioModelArray[index];
    return radioModel;
}

- (void)playingWithProgress:(CGFloat)progress
{
    if (self.type == VoiceTypeRadio) {
        // 计算进度
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setLocale:[NSLocale currentLocale]];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString *currentDate = [formatter stringFromDate:date];
        NSArray *array = [[currentDate componentsSeparatedByString:@" "][1] componentsSeparatedByString:@":"];
        float currentValue = [array[0] floatValue] * 3600 + [array[1] floatValue]* 60 + [array[2] floatValue];
        NSArray *minArray = [self.startTime componentsSeparatedByString:@":"];
        float start = [minArray[0] floatValue] * 60 * 60 + [minArray[1] floatValue] * 60;
        double value = currentValue - start;
        self.scheduleSliderView.value = value;
        // 使滑块无效
        self.scheduleSliderView.frame = CGRectMake(0, CGRectGetMaxY(self.bgImageView.frame), kScreenWidth, 0);
    } else {
        self.scheduleSliderView.frame = CGRectMake(0, CGRectGetMaxY(self.bgImageView.frame) - 15, kScreenWidth, 30);
        self.scheduleSliderView.value = progress;
    }

    [UIView animateWithDuration:0.1 animations:^{
        self.mainVC.icon.transform = CGAffineTransformRotate(self.mainVC.icon.transform, M_PI_4 / 10);
    }];
    if (progress >= (int)self.scheduleSliderView.maximumValue ) {
        [self.player musicPause];
    }
    
    // 加载不出来，或者断网
//    if (self.player.player.status != AVPlayerStatusReadyToPlay) {
//        [self.player musicPause];
//    }
    if (self.player.playerItem.status != AVPlayerStatusReadyToPlay) {
        [self.player musicPlay];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
